﻿using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utility
{
    public static class PolicyUtil
    {
        public static T Retry<T>(int num, Func<T> func)
        {
            var t = Policy.Handle<PolicyRetryException>().Retry(num, (exception, retryCount, context) =>
            {
                Console.WriteLine($"开始第 {retryCount} 次重试：");
            }).Execute<T>(func);

            return t;
        }
        public static void WaitAndRetry(int[] tss, Action func)
        {
            Policy.Handle<PolicyRetryException>()
                .WaitAndRetry(tss.Select(i => TimeSpan.FromSeconds(i))).Execute(func);
        }
        public static T WaitAndRetry<T>(int[] tss, Func<T> func)
        {
            var t = Policy.Handle<PolicyRetryException>()
                .WaitAndRetry(tss.Select(i => TimeSpan.FromSeconds(i))).Execute<T>(func);

            return t;
        }
        public static T WaitAndRetry<TPolicyRetryException, T>(int[] tss, Func<T> func) where TPolicyRetryException : Exception
        {
            var t = Policy.Handle<TPolicyRetryException>()
                .WaitAndRetry(tss.Select(i => TimeSpan.FromSeconds(i))).Execute<T>(func);

            return t;
        }


        public class PolicyRetryException : Exception
        {

        }
    }

}
